#!/usr/bin/env python3
# Licensing : see licensing directory

import os
import re
import misc
from phase0 import phase0

def phase1 (base_dir):
    """This phase looks up the files in path and return them as a list."""
    print ("\nPhase #1: Files listing")
    
    # Define the file list
    filelist = []
    
    # And let's write it
    print ("\tGenerating files list")
    try:
        for root, dirs, files in os.walk(base_dir):
            for name in files:
                if re.match (r'[\w-]*.cr$', name):  # source files must match this expression
                    _, _, tmpname = ("\t" + root + '/' + name).partition(base_dir)
                    tmpname = '.' + tmpname
                    # code enabled in earlier debug phase
                    # print ('\tDebug: '+tmpname)
                    filelist.append(tmpname)
        # Well, a little explanation is needed here : actually, we only build
        # the path of each file, and then make it becoming by './'. Indeed, we
        # already are in the good directory, as verified by phase0, so can we
        # shorten absolute paths to relative ones. It looks better on screen,
        # takes less memory space and doesn't change the parser's behavior. 
    except:
        print("\tError: Can't walk "+base_dir+". Exiting")
        exit(1)
    
    # Test that the folder we are in actually contains source files
    if (not len(filelist)):     # Not very pythonic, but 'if (not filelist):'
                                # doesn't work... Donno why...
        print ("\tError: There are no source files under '"+base_dir+"'. Renewing to phase 0")
        b = phase0()    # Going to the phase0 and taking the new base_dir in b
        c = phase1(b)   # Looping recursively on phase1 with b, and taking 
                        # filelist in c. Yeah, I know, all of that looks like
                        # goto statements... If you know how to do it better
                        # say it.
        return c        # Returning filelist
        
    print ("\tSuccessfully generated files list")
    
    # Sort the filelist
    print ("\tNow sorting it:")
    filelist.sort()
    
    # Then print it to screen in a readable way
    for item in filelist:
        print ("\t\t"+item)
    #print ("\tDebug:", filelist)    # Disabled, debug feature
    
    return misc.fend(filelist)
